package com.zygh.coordinatestore.config;

import com.zygh.coordinatestore.bean.PolygonTypeHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.zygh.coordinatestore.oraclemapper",sqlSessionTemplateRef ="secondSqlSessionTemplate")
public class SecondDataSourceConfig {

  @Autowired
  private DataBase2Properties prop;

////    创建数据源
  @Bean(name = "secondDS")
  @ConfigurationProperties(prefix = "spring.datasource.second")
  public DataSource getSecondDataSource() {
    System.out.println(prop.getUrl());
    DataSource build =  DataSourceBuilder.create()
            .driverClassName(prop.getDriverClassName())
            .url(prop.getUrl())
            .username(prop.getUsername())
            .password(prop.getPassword())
            .build();
    return build;
  }


//  // 创建SessionFactory
  @Bean(name = "secondSqlSessionFactory")
  public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDS") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setVfs(SpringBootVFS.class);
    bean.setTypeHandlersPackage(PolygonTypeHandler.class.getPackage().getName());
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*.xml"));
    return bean.getObject();
  }

  // 创建事务管理器

  @Bean("secondTransactionManger")
  public DataSourceTransactionManager secondTransactionManger(@Qualifier("secondDS") DataSource dataSource){
    return new DataSourceTransactionManager(dataSource);
  }

  // 创建SqlSessionTemplate

  @Bean(name = "secondSqlSessionTemplate")
  public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
    return new SqlSessionTemplate(sqlSessionFactory);
  }

  private Class getType(String type) {
    try {
      return Class.forName(type);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }
}